package com.tms.control;

import com.github.pagehelper.PageInfo;
import com.tms.domain.*;
import com.tms.service.*;
import com.tms.utils.Data;
import com.tms.utils.JsonResult;
import com.tms.utils.description.DescriptionService;
import com.tms.utils.image.ImageService;
import com.tms.utils.token.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import static com.tms.core.constants.RepairConstants.*;
import static com.tms.core.constants.StatusConstants.*;

/**
 * 报修申请
 */
@RestController
@RequestMapping("/api/repairApps")
public class RepairRecordController extends BaseController {

    @Autowired
    private RepairRecordService repairRecordService;

    @Autowired
    private ToolService toolService;

    @Autowired
    private LifeCycleService lifeCycleService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ImageService imageService;

    @Autowired
    private LifeCycleStatusService lifeCycleStatusService;

    @Autowired
    private RepairApplyStatusService repairApplyStatusService;

    @Autowired
    private ToolStatusService toolStatusService;

    @Autowired
    private DescriptionService descriptionService;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static final String PRIMARY_OPERATOR = "ROLE_operator1";

    private static final int MIN_LENGTH_NAME = 7;


    /**
     * 提交报修申请
     *
     * @param toolId  tool的seqId
     * @param description 描叙
     * @param image       图片
     * @param subTime     提交时间
     * @param request     提取token
     * @return
     */
    @PostMapping
    public JsonResult addRepairApp(@RequestParam(value = "toolId") int toolId,
                                   @RequestParam(value = "description") String description, @RequestParam(value = "image") MultipartFile image,
                                   @RequestParam(value = "subTime") String subTime, HttpServletRequest request) {
        Date subDate;
        try {
            subDate = simpleDateFormat.parse(subTime);
        } catch (ParseException e) {
            e.printStackTrace();
            return new JsonResult(ERROR_TIME_PARSE.getStatus(), ERROR_TIME_PARSE.getDesc());
        }
        Tool tool = toolService.findToolById(toolId);
        User submitUser = tokenService.getUserByRequest(request);
        if (submitUser == null) {
            return new JsonResult(ERROR_TOKEN.getStatus(), ERROR_TOKEN.getDesc());
        } else if (tool.getTDef().getWorkcell().getId() != submitUser.getWorkcell().getId()) {
            return new JsonResult(ERROR_OTHER_WORKCELL.getStatus(), ERROR_OTHER_WORKCELL.getDesc());
        }
        String imageName = null;
        if (image != null) {
            imageName = imageService.getName(image, submitUser.getWorkcell().getId(), "repair");
            // 报存图片失败
            if (imageName == null || imageName.length() <= MIN_LENGTH_NAME) {
                return new JsonResult(ERROR.getStatus(), ERROR.getDesc());
            }
        }
        //修改tool的状态
        Status toolStatus = toolStatusService.findById(TOOL_REPAIRING.getStatus());
        tool.setStatus(toolStatus);
        toolService.updateToolById(tool);

        //添加维修记录
        Status repairAppStatus = repairApplyStatusService.findById(REPAIR_SUBMIT.getStatus());
        RepairApp repairApp = new RepairApp(tool, submitUser, description, imageName, subDate, repairAppStatus);
        repairRecordService.createRepairRecord(repairApp);

        return new JsonResult(SUCCESS.getStatus(), SUCCESS.getDesc(), new Data(repairApp));
    }

    /**
     * 根据status分页查看报修记录
     *
     * @param page     页数，默认 1
     * @param pageSize 每页个数，默认 5
     * @param status   状态，默认为-1 即全部状态
     * @author cdx
     * @return 成功则返回记录信息，失败则返回错误信息的JSON
     */
    @GetMapping
    public JsonResult getRecords(@RequestParam(value = "page", defaultValue = "1") int page,
                                 @RequestParam(value = "pageSize", defaultValue = "5") int pageSize,
                                 @RequestParam(value = "status", defaultValue = "-1") int status,
                                 HttpServletRequest request) {
        // 获取token 用于判断权限是否足够
        User user = tokenService.getUserByRequest(request);
        if (user == null) {
            return new JsonResult(ERROR_NULL_USER.getStatus(), ERROR_NULL_USER.getDesc());
        }
        PageInfo<RepairApp> info;
        // 初级与高级用户调用不同的方法，返回参数不同
        if (user.getPosition().getId() > 1 || !PRIMARY_OPERATOR.equals(user.getPosition().getName())) {
            info = repairRecordService.findRepairRecords(page, pageSize, status, user.getWorkcell().getId());
        } else {
            info = repairRecordService.findAllRepairRecordsOfOperatorOne(page, pageSize, status, user);
        }
        return new JsonResult(SUCCESS.getStatus(), SUCCESS.getDesc(), new Data("repairApps", info));
    }

    /**
     * 查看某一确定的报修记录
     *
     * @param id 申请id
     * @author cdx
     * @return 成功则返回记录信息，失败则返回错误信息的JSON
     */
    @GetMapping("/{id}")
    public JsonResult getRecord(@PathVariable(value = "id") int id, HttpServletRequest request) {
        User user = tokenService.getUserByRequest(request);
        if (user == null) {
            return new JsonResult(ERROR_NULL_USER.getStatus(), ERROR_NULL_USER.getDesc());
        }
        RepairApp repairApp = repairRecordService.findRepairRecordById(id);
        if (repairApp != null) {
            // 部门不匹配
            if (repairApp.getSubPerson().getWorkcell().getId() != user.getWorkcell().getId()) {
                return new JsonResult(ERROR_OTHER_WORKCELL.getStatus(), ERROR_OTHER_WORKCELL.getDesc());
            }
            // 是该记录的提交者
            else if (user.getPosition().getName().equals(PRIMARY_OPERATOR) && repairApp.getSubPerson().getId() == user.getId()) {
                return new JsonResult(SUCCESS.getStatus(), SUCCESS.getDesc(), new Data(repairApp));
            }
            // 其他高级用户
            else if (!user.getPosition().getName().equals(PRIMARY_OPERATOR)) {
                return new JsonResult(SUCCESS.getStatus(), SUCCESS.getDesc(), new Data(repairApp));
            }
            // 其他初级用户
            else {
                return new JsonResult(ERROR_NO_POSITION.getStatus(), ERROR_NO_POSITION.getDesc());
            }
        } else {
            return new JsonResult(ERROR_NULL_REPAIR.getStatus(), ERROR_NULL_REPAIR.getDesc());
        }
    }

    /**
     * 处理报修申请
     *
     * @param id      报修申请id
     * @param map     存放参数-time-处理时间
     * @param request 获取token以取得用户
     * @author Liao
     * @return 成功处理返回记录信息，失败返回错误信息
     */
    @PatchMapping("{id}")
    public JsonResult manageRepairRecord(@PathVariable(value = "id") int id, @RequestBody Map<String, String> map,
                                         HttpServletRequest request) {
        RepairApp repairApp = repairRecordService.findRepairRecordById(id);
        // 判断是否存在对应 id 的记录
        if (repairApp == null) {
            return new JsonResult(ERROR_NULL_REPAIR.getStatus(), ERROR_NULL_REPAIR.getDesc());
        }

        User checker = tokenService.getUserByRequest(request);
        if (checker == null) {
            return new JsonResult(ERROR_NULL_USER.getStatus(), ERROR_NULL_USER.getDesc());
        }

        // 不同部门
        else if (checker.getWorkcell().getId() != repairApp.getSubPerson().getWorkcell().getId()) {
            return new JsonResult(ERROR_OTHER_WORKCELL.getStatus(), ERROR_OTHER_WORKCELL.getDesc());
        }

        // 权限不足，初级用户不可以进行该操作
        else if (checker.getPosition().getId() == 1 || PRIMARY_OPERATOR.equals(checker.getPosition().getName())) {
            return new JsonResult(ERROR_NO_POSITION.getStatus(), ERROR_NO_POSITION.getDesc());
        }

        // repair 状态已经是终止状态
        else if (repairApp.getStatus().getId() != REPAIR_SUBMIT.getStatus()) {
            return new JsonResult(ERROR_REPEAT_STATUS.getStatus(), ERROR_REPEAT_STATUS.getDesc());
        }
        // 获取处理时间
        String checkTime = map.get("checkTime");
        Date checkDate;
        try {
            checkDate = simpleDateFormat.parse(checkTime);
        } catch (ParseException e) {
            e.printStackTrace();
            return new JsonResult(ERROR_TIME_PARSE.getStatus(), ERROR_TIME_PARSE.getDesc());
        }
        int statusId = Integer.parseInt(map.get("status"));
        if (statusId != REPAIR_SUCCESS.getStatus() && statusId != REPAIR_FAILED.getStatus()) {
            return new JsonResult(ERROR_STATUS.getStatus(), ERROR_STATUS.getDesc());
        }

        // 时间逻辑判断， check 时间不可以早于 submit 时间
        if (checkDate.before(repairApp.getSubTime())) {
            return new JsonResult(ERROR_DATE_BEFORE.getStatus(), ERROR_DATE_BEFORE.getDesc());
        }
        // 修改维修状态
        Status repairAppStatus = repairApplyStatusService.findById(statusId);
        repairApp.setCheckPerson(checker);
        repairApp.setCheckTime(checkDate);
        repairApp.setStatus(repairAppStatus);
        repairRecordService.updateRepairRecordById(repairApp);

        // 添加 lifeCycle 记录
        Status lifeCycleStatus = lifeCycleStatusService.findById(LIFE_REPAIR.getStatus());
        String description = descriptionService.getDescription(repairApp);
        LifeCycle lifeCycle = new LifeCycle(repairApp.getTool(), lifeCycleStatus, repairApp.getId(), checkDate, description);
        lifeCycleService.createLifeCycle(lifeCycle);

        // 修改模具状态
        Status toolStatus = toolStatusService.findById(TOOL_INDOOR.getStatus());
        Tool tool = repairApp.getTool();
        tool.setStatus(toolStatus);
        toolService.updateToolById(tool);
        return new JsonResult(SUCCESS.getStatus(), SUCCESS.getDesc(), new Data(repairApp));
    }
}